package top.kikt.book.core.handlers

import okhttp3.HttpUrl.Companion.toHttpUrl
import org.jsoup.nodes.Document
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.util.bookText

class `3UXiaoShuo` : BaseBookHandler() {
    override val host: String
        get() = "www.3uxiaoshuo.com"

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        val title = document.selectXpath("/html/body/div[4]/div[1]/div/h1/a").text()
        val author = document.selectXpath("/html/body/div[4]/div[1]/div/p[2]/a").text().removePrefix("作者：")
        val coverUrl = document.selectXpath("/html/body/div[4]/div[1]/a/img").attr("src").let {
            url.toHttpUrl().resolve(it)
        }

        return BookMetaEntity(title, url, url, author, coverUrl.toString())
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val result = ArrayList<ChapterMetaEntity>()

        var doc = document

        var page = 1

        while (true) {
            println("当前正在请求第 $page 页")
            val startIndex = result.size
            val list = doc.selectXpath("/html/body/div[4]/div[@id='list']/ul/li")
            list.mapIndexed { index, element ->
                val a = element.selectXpath("a")
                val title = a.text()
                val url = menuUrl.toHttpUrl().resolve(a.attr("href")).toString()
                ChapterMetaEntity(title, startIndex + index, url, element)
            }.apply {
                result.addAll(this)
            }

            val nextLink = doc.selectXpath("/html/body/div[4]/div[@id='pages']/a[text()='下一页']")

            if (nextLink.hasAttr("href")) {
                val nextPageHref = nextLink.attr("href")
                println("nextPageHref: $nextPageHref")
                val nextUrl = menuUrl.toHttpUrl().resolve(nextPageHref)
                doc = nextUrl?.toDocument() ?: throw Exception("Get next page failed")
                page++
            } else {
                break
            }
        }

        println("3uxiaoshuo 获取到: ${result.size} 章内容")

        return result.apply {
            println(this.joinToString("\n") { it.name })
        }
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        var doc = chapterMetaEntity.toDocument() ?: return null
        val url = chapterMetaEntity.url.toHttpUrl()
        val sb = StringBuilder()
        var page = 1
        while (true) {
//            println("当前正在请求 $url 第 $page 页")
            val content = doc.selectXpath("/html/body/div[4]/div[2]/p").bookText()
            sb.appendLine(content)

            // next page link
            val nextA = doc.selectXpath("/html/body/div[4]/div[3]/span[2]/a[text()='下一页']")
            if (nextA.hasAttr("href")) {
                val nextPageHref = nextA.attr("href")
                println("nextPageHref: $nextPageHref")
                val nextUrl = url.resolve(nextPageHref)
                doc = nextUrl?.toDocument() ?: throw Exception("Get next page failed")
                page++
            } else {
                break
            }
        }

        return chapterMetaEntity.toChapterMetaEntity(sb.toString())
    }
}